/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnFocusChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

/**Activity that shows a list of all Profiles*/
public class ProfileList extends Activity implements View.OnClickListener{
    protected static Database mDbHelper;
    protected Boolean ShowRules;
    private Long MenOpenFor = -1L;
    private static final int ScrollView_ID = 999;
    private static final int MEN_DELETE_ID = Menu.FIRST;
    private static final int MEN_SHORT_CUT = Menu.FIRST+1;
    private static final int MEN_AKT_TEMP = Menu.FIRST+2;
    private static final int MENU_DICARD_PROFILES = Menu.FIRST+3;
    private static final int MENU_EXIT = Menu.FIRST+4;

    public void onClick(View v) {
    	final Context c = v.getContext();
    	
    	if(v.getId()==R.id.ToggleButton01)
    	{
            // Perform action on click - activate or deactivate a Profile
        	final long id = Long.parseLong((String) ((View) v.getParent()).getTag());
        	
        	if(((ToggleButton)v).isChecked())
        	{
        		new Thread() {
                    public void run() {
                    	TimedProfiles.ToggelProfile(mDbHelper, c, id,1);
                    }
        		}.start();
        	}else{
        		new Thread() {
                    public void run() {
                    	TimedProfiles.ToggelProfile(mDbHelper, c, id,0);
		            }
				}.start();
			}
    	}else{
    		// Perform action on click
        	if(TimedProfiles.car_mode)
        	{
        		//dont edit, toggle!
        		((ViewGroup) v).getChildAt(((ViewGroup) v).getChildCount()-1).performClick();
        	}else{
	            Intent Opener = new Intent(v.getContext(), ProfileEditor.class); 
	            
	            Opener.putExtra(ProfileEditor.OpenParam_ProfileID, (CharSequence)v.getTag());
	        	
	            v.getContext().startActivity(Opener);
        	}
    	}
    }

    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		final long id = Long.parseLong((String)v.getTag());
		if(id==-1)
		{
			return;
		}
		Cursor notesCursor = mDbHelper.fetchProfile(id);
		if(notesCursor!=null)
		{
			menu.setHeaderTitle(notesCursor.getString(notesCursor.getColumnIndex(Database.P_KEY_NAME)));
			notesCursor.close();
		}
		MenOpenFor = id;
        menu.add(0, MEN_DELETE_ID, 0, R.string.menu_delete).setOnMenuItemClickListener(Contextmen);
        menu.add(0, MEN_SHORT_CUT, 0, R.string.menu_shortcut).setOnMenuItemClickListener(Contextmen);
        //TODO? menu.add(0, MEN_AKT_TEMP, 0, R.string.menu_temp_akt).setOnMenuItemClickListener(Contextmen);
        
	}
	private MenuItem.OnMenuItemClickListener Contextmen = new
	MenuItem.OnMenuItemClickListener(){

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			onContextItemSelected(item);
			return false;
		}
		
		
	};
    //@Override
	public boolean onContextItemSelected(MenuItem item) {
		
		if(MenOpenFor==-1L)
    	{
    		return true;
    	}
		switch(item.getItemId()) {
    	case MEN_DELETE_ID:
    		mDbHelper.deleteProfile(MenOpenFor);
    		setupTableView(this);
	        return true;
    	case MEN_SHORT_CUT:
    		Intent intent = ShortCutHandler.createShortCutData(this, MenOpenFor, mDbHelper);
    		if(intent==null)
    		{
    			return true;
    		}
        	sendBroadcast(intent);
	        return true;
    	case MEN_AKT_TEMP:
    		//show date picker
    		Toast.makeText(getApplicationContext(), getString(R.string.menu_temp_akt), Toast.LENGTH_LONG).show();
    		return true;
		}
		return super.onContextItemSelected(item);
	}
	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		super.onCreateOptionsMenu(menu);

		//Help
		final Intent helpIntent = new Intent(this, OnlineHelp.class);//("com.twofortyfouram.locale.intent.action.HELP");
		helpIntent.putExtra(OnlineHelp.HELP_URL, OnlineHelp.HELP_URL_PRE+"profiles");
		helpIntent.putExtra(TimedProfiles.INTENT_TITLE, getTitle().toString());
		
		menu.add(0, MENU_DICARD_PROFILES, 0, R.string.profiles_clear)
		.setIcon(R.drawable.wipe_men).getItemId();

		menu.add(0, MENU_EXIT, 0, R.string.men_exit)
		 .setIcon(android.R.drawable.ic_lock_power_off).getItemId();

		menu.add(R.string.onlinehelp)
			.setIcon(android.R.drawable.ic_menu_help).setIntent(helpIntent);

		//New
		MenuItem i = menu.add(R.string.profile_add).setIcon(android.R.drawable.ic_menu_add);
		if(TimedProfiles.car_mode)
		{
			i.setEnabled(false);
		}else{
			Intent NewProfile = new Intent(this, ProfileEditor.class); 
	        NewProfile.putExtra(ProfileEditor.OpenParam_ProfileID, "-1");
			i.setIntent(NewProfile);
		}

		return true;
	}
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item)
	{
		switch (item.getItemId())
		{
			case MENU_EXIT:
			{
				finish();
				return true;
			}
			case MENU_DICARD_PROFILES:
			{
			  	Cursor notesCursor = mDbHelper.fetchAllProfiles();

				if(notesCursor!=null)
				 {
				  	final int ia = notesCursor.getColumnIndex(Database.P_KEY_ACTIVE),
						 	ir = notesCursor.getColumnIndex(Database.P_KEY_ROWID);
				  do{
					  if(1==notesCursor.getInt(ia))
					  {
						  TimedProfiles.ToggelProfile(mDbHelper, this.getApplicationContext(), notesCursor.getLong(ir),0);
					  }
				  }while(notesCursor.moveToNext() != false);
				  notesCursor.close();
				 }
				
				mDbHelper.discardProfiles();
	    		setupTableView(this);
				return true;
			}
		}

		return super.onOptionsItemSelected(item);
	}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new Database(this);
        
        ShowRules = false;
        // wrap the table in a scrollpane
        ScrollView scrollPane = new ScrollView(this);
        scrollPane.setLayoutParams(new LinearLayout.LayoutParams(
		          LinearLayout.LayoutParams.FILL_PARENT,
		          LinearLayout.LayoutParams.WRAP_CONTENT
		      ));
        scrollPane.setId(ScrollView_ID);
        setContentView(scrollPane);
        //onResume will set the list
    }

    @Override
	public void onDestroy()
    {
    	super.onDestroy();
    }
    
    @Override
    protected void onPause() {
    	mDbHelper.close();
        super.onPause();
        //saveState();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(!ShowRules)
        {
        	//rules handle that theirselfs
        	mDbHelper.open();
        }
        setupTableView(this);
    }
    public void setupTableView(Activity activity) {
    	LinearLayout table = new LinearLayout(activity);
  	  table.setLayoutParams(new LinearLayout.LayoutParams(
		          LinearLayout.LayoutParams.FILL_PARENT,
		          LinearLayout.LayoutParams.FILL_PARENT
		      ));
  	  table.setOrientation(LinearLayout.VERTICAL);

  	//Print Values
  	Cursor notesCursor = null;
  	  if(ShowRules)
  	  {
  		notesCursor = mDbHelper.fetchAllRules();
  	  }else{
  		notesCursor = mDbHelper.fetchAllProfiles();
  	  }
	if(notesCursor!=null)
	 {
	  	int in, ia, ir, ic;
	  	  if(ShowRules)
	  	  {
			 in = notesCursor.getColumnIndex(Database.R_KEY_NAME);
			 ia = notesCursor.getColumnIndex(Database.R_KEY_ACTIVE);
			 ir = notesCursor.getColumnIndex(Database.R_KEY_ROWID);
			 ic = notesCursor.getColumnIndex(Database.R_KEY_ICON);
	  	  }else{
	 		 in = notesCursor.getColumnIndex(Database.P_KEY_NAME);
			 ia = notesCursor.getColumnIndex(Database.P_KEY_ACTIVE);
			 ir = notesCursor.getColumnIndex(Database.P_KEY_ROWID);
			 ic = notesCursor.getColumnIndex(Database.P_KEY_ICON);
	  	  }
	  do{
		  int ico = notesCursor.getInt(ic);
		  if(ico==0)
		  {
			  ico = R.drawable.icon;
		  }
		  
		table.addView(buildRow(notesCursor.getLong(ir), notesCursor.getString(in), ico, notesCursor.getInt(ia)));
		  
		ImageView delimiter = new ImageView(this);
		delimiter.setImageResource(android.R.drawable.divider_horizontal_dim_dark);
		table.addView(delimiter);
			
	  }while(notesCursor.moveToNext() != false);
	  notesCursor.close();
	 }
	  
	if(!TimedProfiles.car_mode)
	{
		//new button
		if(ShowRules)
		{
			table.addView(buildRow(-1L, getText(R.string.rule_add), R.drawable.time, -1));
		}else{
			table.addView(buildRow(-1L, getText(R.string.profile_add), R.drawable.create, -1));
		}
	}
	
	//registerForContextMenu(table);


  	((ScrollView)activity.findViewById(ScrollView_ID)).removeAllViews();
  	((ScrollView)activity.findViewById(ScrollView_ID)).addView(table);

  }
    
    private View buildRow(Long id, CharSequence charSequence, int icoRes, int button_val)
    {
    	final Context activity = findViewById(ScrollView_ID).getContext();
    	
    	View row = LayoutInflater.from(activity).inflate(R.layout.row_button, null);
    	
		  ImageView icon = (ImageView) row.findViewById(R.id.icon);
	      icon.setAdjustViewBounds(true);
	      icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
	      icon.setMaxHeight(TimedProfiles.max_icon_h);
	      icon.setMinimumHeight(TimedProfiles.min_icon_h);
	      icon.setImageResource(icoRes);//.setImageDrawable(image);

	      TextView text = (TextView) row.findViewById(R.id.firstLine);
	      text.setText(charSequence);

	      if(button_val==0 || button_val==1)
	      {
		      ToggleButton button = (ToggleButton) row.findViewById(R.id.ToggleButton01);
		      
		      button.setChecked(button_val==1?true:false);
		      
		      button.setOnClickListener(this);
	      }else{
	    	  row.findViewById(R.id.ToggleButton01).setVisibility(View.GONE);
	      }
	      row.setTag(String.format("%d", id));
		  	if(!TimedProfiles.car_mode)
		  	{
		      row.setLongClickable(true);
		      row.setOnCreateContextMenuListener((OnCreateContextMenuListener) activity);
		  	}
	      row.setOnClickListener(this);
	      row.setFocusable(true);
	      row.setOnFocusChangeListener(ItemFoki);
	      //row.offsetTopAndBottom(offset)
	     // row.setBackgroundColor(Color.argb(255, 24, 24, 24));
	      
	      return row;
    }
    
    private OnFocusChangeListener ItemFoki = new OnFocusChangeListener()
    {
	  	@Override
	  	public void onFocusChange(View v, boolean hasFocus) {
	  		v.setBackgroundColor(hasFocus?Color.argb(200, 61, 93, 255):Color.argb(200, 24, 24, 24));
	  	}
    };
}